﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Utility;
using Utility.jqGrid;
using Utility.Comm;
using Hxj.Data;
using Utility.Json;
using Utility.Log;
using System.Reflection;
using System.Web.SessionState;
using System.Web;

namespace BaseUI.Base
{

    public class HandlerBase_Class : IHttpHandler, IRequiresSessionState
    {
        #region  Context、Request、Response、Server、Session、Application、Cache、objRetData、UserInfo、Account、IP
        /// <summary>
        /// 获取与该页关联的 HttpContext 对象。
        /// </summary>
        public HttpContext Context { get; private set; }
        /// <summary>
        /// 获取请求的页的 HttpRequest 对象。
        /// </summary>
        public HttpRequest Request { get; private set; }
        /// <summary>
        /// 获取与该 Page 对象关联的 HttpResponse 对象。该对象使您得以将 HTTP 响应数据发送到客户端，并包含有关该响应的信息。
        /// </summary>
        public HttpResponse Response { get; private set; }
        /// <summary>
        /// 获取 Server 对象
        /// </summary>
        public HttpServerUtility Server { get; private set; }
        /// <summary>
        /// 获取 ASP.NET 提供的当前 Session 对象。
        /// </summary>
        public HttpSessionState Session { get; private set; }
        /// <summary>
        /// 为当前 Web 请求获取 HttpApplicationState 对象。
        /// </summary>
        public HttpApplicationState Application { get; private set; }
        /// <summary>
        /// 获取当前应用程序域的System.Web.Caching.Cache 对象
        /// </summary>
        public System.Web.Caching.Cache Cache { get; private set; }
        /// <summary>
        /// 返回数据的 json 字符串
        /// </summary>
        public JsonRetData objRetData { get; private set; }
        #endregion


        /// <summary>
        /// IP
        /// </summary>
        public string IP
        {
            get
            {
                string _ip = string.Empty;
                try
                {
                    if (Context.Request.ServerVariables["HTTP_VIA"] != null) // using proxy
                    {
                        _ip = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
                    }
                    else// not using proxy or can't get the Client IP
                    {
                        _ip = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
                    }
                }
                catch
                { }
                return _ip;
            }
        }


        #region 实例化接口,初始化数据
        /// <summary>
        /// 实例化接口,初始化数据
        /// </summary>
        public HandlerBase_Class()
        {
            this.InitHttpContext(System.Web.HttpContext.Current);
        }
        #endregion

        #region ProcessRequest_Instance反射方法
        /// <summary>
        /// 反射方法
        /// </summary>
        public void ProcessRequest_Instance()
        {
            try
            {
                this.Response.ContentType = "text/plain";
                string methodName = this.Request["method"];
                Type type = this.GetType();
                MethodInfo method = type.GetMethod(methodName);
                if (method == null)
                {
                    throw new Exception("method is null");
                }
                method.Invoke(this, null);
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("\r\n账号:" + Context.User.Identity.Name + "\r\n客户机IP:" + Request.UserHostAddress + "\r\n错误地址:" + Request.Url + "\r\n异常信息:" + ex.Message, ex);
                this.GetFailureJson("出现异常，请管理员查看系统日志");
            }
        }
        #endregion

        #region InitHttpContext初始化HTTP上下文参数
        /// <summary>
        /// 初始化HTTP上下文参数
        /// </summary>
        /// <param name="context"></param>
        public void InitHttpContext(HttpContext context)
        {
            this.Context = context;
            this.Application = context.Application;
            this.Request = context.Request;
            this.Response = context.Response;
            this.Server = context.Server;
            this.Session = context.Session;
            this.Cache = context.Cache;
            this.objRetData = new JsonRetData();
        }
        #endregion

        #region 快捷返回成功或失败Json值方法
        /// <summary>
        /// 成功返回json
        /// </summary>
        protected void GetSuccessJson()
        {
            GetSuccessJson(string.Empty, string.Empty, string.Empty);
        }
        /// <summary>
        /// 成功返回json 可自定义返回数据
        /// </summary>
        protected void GetSuccessJson(string strMessage)
        {
            GetSuccessJson(string.Empty, string.Empty, strMessage);
        }
        /// <summary>
        /// 成功返回json 可自定义返回数据
        /// </summary>
        /// <param name="strRetData">成功返回Data</param>
        /// <param name="strRetCode">成功返回代码</param>
        /// <param name="strMessage">成功返回的信息</param>
        protected void GetSuccessJson(string strRetData, string strRetCode, string strMessage)
        {
            objRetData.State = "true";
            objRetData.Message = strMessage;
            objRetData.RetCode = strRetCode;
            objRetData.RetData = strRetData;
            Response.Write(objRetData.AssemblyJson());
        }
        /// <summary>
        /// 成功返回json 可自定义返回数据、当返回的数据时json格式的时候调用
        /// </summary>
        /// <param name="strRetData">成功返回Data</param>
        /// <param name="strRetCode">成功返回代码</param>
        /// <param name="strMessage">成功返回的信息</param>
        protected void GetSuccessJson_RetDataJson(string strRetData, string strRetCode, string strMessage)
        {
            objRetData.State = "true";
            objRetData.Message = strMessage;
            objRetData.RetCode = strRetCode;
            objRetData.RetData = strRetData;
            Response.Write(objRetData.AssemblyJson());
        }
        /// <summary>
        /// 失败返回json
        /// </summary>
        protected void GetFailureJson()
        {
            GetFailureJson(string.Empty, string.Empty, string.Empty);
        }
        /// <summary>
        /// 失败返回json 可自定义错误信息
        /// </summary>
        protected void GetFailureJson(string strMsg)
        {
            GetFailureJson(string.Empty, string.Empty, strMsg);
        }
        /// <summary>
        /// 成功返回json 可自定义返回数据
        /// </summary>
        /// <param name="strRetData">成功返回Data</param>
        /// <param name="strRetCode">成功返回代码</param>
        /// <param name="strMessage">成功返回的信息</param>
        protected void GetFailureJson(string strRetData, string strRetCode, string strMessage)
        {
            objRetData.State = "false";
            objRetData.Message = strMessage;
            objRetData.RetCode = strRetCode;
            objRetData.RetData = strRetData;
            Response.Write(objRetData.AssemblyJson());
        }
        #endregion

        #region 快捷返回值方法 SetOrderBy、SetPageConditon
        /// <summary>
        /// 设置排序
        /// </summary>
        /// <param name="orderField">排序字段</param>
        /// <param name="orderType">desc或asc</param>
        /// <returns>OrderByClip</returns>
        protected OrderByClip SetOrderBy(string orderField, string orderType)
        {
            OrderByClip order;
            orderField = orderField.Replace("Str", "");
            if (String.Equals(orderType, "desc", StringComparison.CurrentCultureIgnoreCase))
            {
                order = new OrderByClip(orderField, OrderByOperater.DESC);
            }
            else
            {
                order = new OrderByClip(orderField, OrderByOperater.ASC);
            }
            return order;
        }
        /// <summary>
        /// 设置翻页类
        /// </summary>
        /// <param name="where">WhereClip条件</param>
        /// <param name="order">排序OrderByClip</param>
        /// <returns>PagerCondition</returns>
        protected PagerCondition SetPageConditon(WhereClip where, OrderByClip order)
        {
            int pageIndex = ParamsOfRequest.page;
            int pageSize = ParamsOfRequest.rows;
            var pageConditon = new PagerCondition { PageSize = pageSize, CurrentPage = pageIndex, ComplexSearchCondition = where, OrderBy = order };
            return pageConditon;
        }
        /// <summary>
        /// 设置翻页类
        /// </summary>
        /// <param name="where">WhereClip条件</param>
        /// <param name="orderField">排序字段</param>
        /// <param name="orderType">desc或asc</param>
        /// <returns>PagerCondition</returns>
        protected PagerCondition SetPageConditon(WhereClip where, string orderField, string orderType)
        {
            return this.SetPageConditon(where, this.SetOrderBy(orderField, orderType));
        }
        /// <summary>
        /// 设置翻页类,排序字段通过Request来获取
        /// </summary>
        /// <param name="where">WhereClip条件</param>
        /// <returns>PagerCondition</returns>
        protected PagerCondition SetPageConditon(WhereClip where)
        {
            //获取同一类型业务的列表
            string orderField = ParamsOfRequest.sort;
            string orderType = ParamsOfRequest.order;
            if (string.IsNullOrEmpty(orderField))
            {
                orderField = "CreateTime";
            }
            if (orderType != "desc" && orderType != "asc")
            {
                orderType = "desc";
            }
            return this.SetPageConditon(where, orderField, orderType);
        }
        /// <summary>
        /// 获取翻页类,排序字段和类别通过Request来获取
        /// </summary>
        /// <param name="where">WhereClip条件</param>
        /// <returns>PagerCondition</returns>
        protected PagerCondition GetPageConditon(WhereClip where)
        {
            return GetPageConditon(where, ParamsOfRequest.jqGridSortField, ParamsOfRequest.jqGridSortBy);
        }
        /// <summary>
        /// 获取翻页类
        /// </summary>
        /// <param name="where">WhereClip条件</param>
        /// <param name="strSortFiled">排序字段</param>
        /// <param name="strSortBy">排序类别,desc或asc</param>
        /// <returns>PagerCondition</returns>
        protected PagerCondition GetPageConditon(WhereClip where, string strSortFiled, string strSortBy)
        {
            var pageConditon = new PagerCondition();
            string strWhere = GetJqGridWhere();
            if (strWhere.Length > 0)
            {
                where = where.And(strWhere);
            }
            int numberOfRows = ParamsOfRequest.jqGridRows;
            int pageIndex = ParamsOfRequest.jqGridPageIndex;
            if (strSortFiled.Length > 0)
            {
                if (String.Equals(strSortBy, "desc", StringComparison.CurrentCultureIgnoreCase))
                {
                    pageConditon.OrderBy = new OrderByClip(strSortFiled, OrderByOperater.DESC);
                }
                else
                {
                    pageConditon.OrderBy = new OrderByClip(strSortFiled, OrderByOperater.ASC);
                }
            }
            pageConditon.CurrentPage = pageIndex.ToSafeInt();
            pageConditon.PageSize = numberOfRows.ToSafeInt();
            pageConditon.ComplexSearchCondition = where;
            return pageConditon;
        }
        /// <summary>
        /// 获取JqGrid条件值
        /// </summary>
        /// <returns></returns>
        private static string GetJqGridWhere()
        {
            string strWhere = string.Empty;
            string _search = ParamsOfRequest.Request("_search");
            if (_search == "true")
            {
                string strField = ParamsOfRequest.Request("searchField");
                string strFilters = ParamsOfRequest.Request("filters");
                if (strFilters.Length > 0)
                {
                    strWhere = jqGridJsonHelper.jqGridFilte(strFilters);
                }
                else
                {
                    if (strField.Length > 0 && strField != "act")
                    {
                        string strFieldData = ParamsOfRequest.Request("searchString");
                        string strSearchOper = ParamsOfRequest.Request("searchOper");
                        jqGridFilterRules jqfilter = new jqGridFilterRules();
                        jqfilter.Op = strSearchOper;
                        jqfilter.Field = strField;
                        jqfilter.Data = strFieldData;
                        strWhere = jqGridJsonHelper.jqGridFilte(jqfilter);
                    }
                }
            }
            return strWhere;
        }
        #endregion


        public virtual void ProcessRequest(HttpContext httpContext)
        {

        }


        /// <summary>
        /// 是否可重用
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}